<script setup lang="ts">
import { ref, inject, computed } from "vue"; //导入vue函数
import { ElMessage } from "element-plus"; //导入消息框
import { useCart } from "@/stores/cart"; //导入cart状态文件

//执行方法获得cartStore对象
const cartStore = useCart();

//购买的商品信息
const props = defineProps(["orderPrice", "selectGoods"]);

//通过依赖注入，共享父组件中的响应数据对象
var isShow = inject<any>("isShowPay"); //dialog是否显示

//支付方式
const payway = ref("wx");

//订单编写
const orderId = ref("");

//订单结算的倒计时(30分钟)
const countdown = ref(1800);

//订单结算的倒计时 - 显示字符串
const countdownStr = computed(() => {
  const minute = Math.floor(countdown.value / 60);
  const second = countdown.value % 60;
  return (
    (minute < 10 ? "0" + minute : minute) +
    ":" +
    (second < 10 ? "0" + second : second)
  );
});

//定时器对象
var timer: any = null;

//Dialog打开的回调函数
function initOrder() {
  //初始化倒计时
  countdown.value = 1800;
  //生成订单编号
  orderId.value = "DD" + Date.now();
  //倒计时
  timer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      window.clearInterval(timer);
      ElMessage.warning("支付超时，请重新下单");
      isShow.value = false; //关闭当前窗口
    }
  }, 1000);
}

//Dialog关闭的回调函数
function destoryOrder() {
  window.clearInterval(timer);
}

//模拟支付成功
function pay() {
  ElMessage.success("支付成功");
  if (props.selectGoods) {
    cartStore.delPayGoods(props.selectGoods); //删除已下单购买的商品
  }
  isShow.value = false; //关闭当前窗口
}
</script>

<template>
  <el-dialog
    v-model="isShow"
    title="订单支付"
    width="400"
    center
    @open="initOrder"
    @close="destoryOrder"
  >
    <!--显示内容-->
    <section>
      <div>订单号：{{ orderId }}</div>
      <div>
        支付金额：<span>￥{{ props.orderPrice.toFixed(2) }}</span>
      </div>
      <div>
        <el-radio-group v-model="payway" size="large">
          <el-radio-button label="微信支付" value="wx" />
          <el-radio-button label="支付宝" value="alipay" />
        </el-radio-group>
      </div>
      <div><img src="@/assets/images/ewm.png" /></div>
      <div>请使用{{ payway == "wx" ? "微信" : "支付宝" }}扫码支付</div>
      <div>支付剩余时间：{{ countdownStr }}</div>
      <div>
        <el-button type="primary" size="large" @click="pay"
          >模拟支付成功</el-button
        >
      </div>
    </section>
  </el-dialog>
</template>

<style scoped>
section {
  text-align: center;
}
section > div {
  margin: 20px auto;
}
section > div > span {
  color: #cf4444;
  font-size: 20px;
  font-weight: bold;
}
section > div > .el-button {
  width: 160px;
}
section > div:nth-child(4) {
  border: 1px solid #e4e4e4;
  border-radius: 5px;
  width: 160px;
  height: 160px;
  display: flex;
  justify-content: center;
  align-items: center;
}
section > div:nth-child(4) > img {
  width: 150px;
  height: 150px;
}
</style>
